package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMMatch;
import com.shwread.android.qysw.step.dto.HMMatchDto;
import com.shwread.android.qysw.step.dto.HMOneFriendMatchDetailsDto;
import com.shwread.android.qysw.step.dto.LqswHealthMatch;
import com.shwread.android.qysw.step.dto.Player;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.RectImageView;
import com.shwread.android.qysw.tools.TimeHelper;
import com.shwread.android.qysw10000182.R;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/4/3.
 */
public class FriendPKDetailActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.center_img)
    ImageView centerImg;
    @InjectView(R.id.leave_start_time_text)
    TextView leaveStartTimeText;
    @InjectView(R.id.left_head_icon_img)
    RectImageView leftHeadIconImg;
    @InjectView(R.id.center_text)
    TextView centerText;
    @InjectView(R.id.right_head_icon_img)
    RectImageView rightHeadIconImg;
    @InjectView(R.id.pk_item_layout)
    FrameLayout pkItemLayout;
    @InjectView(R.id.left_name_text)
    TextView leftNameText;
    @InjectView(R.id.right_name_text)
    TextView rightNameText;
    @InjectView(R.id.no_accept_layout)
    RelativeLayout noAcceptLayout;
    @InjectView(R.id.no_accept_img)
    ImageView noAcceptImg;
    @InjectView(R.id.left_step)
    TextView leftStep;
    @InjectView(R.id.right_step)
    TextView rightStep;
    @InjectView(R.id.step_layout)
    LinearLayout stepLayout;


    @InjectView(R.id.left_daily_step)
    TextView leftDailyStep;
    @InjectView(R.id.right_daily_step)
    TextView rightDailyStep;
    @InjectView(R.id.left_daily_w)
    TextView leftDailyW;
    @InjectView(R.id.right_w)
    TextView rightW;
    @InjectView(R.id.left_l)
    TextView leftL;
    @InjectView(R.id.right_l)
    TextView rightL;
    @InjectView(R.id.left_d)
    TextView leftD;
    @InjectView(R.id.right_d)
    TextView rightD;
    @InjectView(R.id.history_win_layout)
    LinearLayout historyWinLayout;
    List<Player> players;
    @InjectView(R.id.pk_button)
    RelativeLayout pkButton;
    HMMatch hmMatch;
    @InjectView(R.id.pk_text)
    TextView pkText;
    boolean isFrompush;
    @InjectView(R.id.see_all_pk_button)
    RelativeLayout seeAllPkButton;
    Timer timer = new Timer();
    LqswHealthMatch lqswHealthMatch;
    TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_pk_detail_activity);
        ButterKnife.inject(this);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleText.setText("好友PK");
        Intent intent = getIntent();
        isFrompush = intent.getExtras().getBoolean("push", false);
        if (isFrompush) {
            String matchId = intent.getStringExtra("matchId");
            HashMap<String, String> params = new HashMap<>();
            params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
            params.put("enterpriseId", AppConfig.getEnterpriseId());
            params.put("matchId", matchId);
            String unstartUrl = "/hzlqswserver/health/game/getMatch";
            HashMap<String, String> hashMapUrl2 = new HashMap<>();
            hashMapUrl2.put("url", unstartUrl);
            MyAsynctask asynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
                @Override
                public void requestSuccess(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String res = jsonObject.optString("returnObject");
                        HMMatchDto hmMatchDto = HMMatchDto.parserJson(res);
                        hmMatch = hmMatchDto.getHMMatch();
                        setView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
            asynctask.execute(hashMapUrl2, params);
        } else {
            hmMatch = (HMMatch) intent.getSerializableExtra("hmMatch");
            setView();
        }



    }

    private void setView(){
        lqswHealthMatch = hmMatch.getLqswHealthMatch();
        players = hmMatch.getPlayers();
        int state = hmMatch.getLqswHealthMatch().getState();//(1),未开始，(2)开始，(3)结束，(4)失效


        int judge = 0;
        int myState = 0;
        for (int k = 0; k < players.size(); k++) {
            if (players.get(k).getIsAccept() == 0 && players.get(k).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                myState = 1;
            }
            if (players.get(k).getIsAccept() == 0 && players.get(k).getUserId() != UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {

                judge = 1;
            }
        }
        //int state = hmMatch.getLqswHealthMatch().getState();//(1),未开始，(2)开始，(3)结束，(4)失效
        if (judge == 1) {//好友未接受
            noAcceptLayout.setVisibility(View.VISIBLE);
            noAcceptImg.setVisibility(View.VISIBLE);
            //centerText.setText("等待对方明日接受PK");
        } else if (myState == 1) {//我未接受
            noAcceptLayout.setVisibility(View.INVISIBLE);
            noAcceptImg.setVisibility(View.VISIBLE);
            //centerText.setText("点击接受比赛");
            pkButton.setVisibility(View.VISIBLE);
            pkButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
                    params.put("enterpriseId", AppConfig.getEnterpriseId());
                    params.put("matchId", hmMatch.getLqswHealthMatch().getMatchId() + "");

                    String unstartUrl = "hzlqswserver/health/game/accept";
                    HashMap<String, String> hashMapUrl2 = new HashMap<>();
                    hashMapUrl2.put("url", unstartUrl);
                    MyAsynctask asynctask = new MyAsynctask(FriendPKDetailActivity.this, new MyAsynctask.RequestListener() {
                        @Override
                        public void requestSuccess(String result) {
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(result);
                                String res = jsonObject.optString("resultCode");
                                if ("1000".equals(res)) {
                                    Toast.makeText(FriendPKDetailActivity.this, "接受成功", Toast.LENGTH_LONG).show();
                                    pkButton.setVisibility(View.INVISIBLE);
                                    MyHistoryGame();
                                    noAcceptImg.setVisibility(View.INVISIBLE);
                                    if (TimeHelper.isToday(lqswHealthMatch.getStartTime())) {
                                        centerText.setVisibility(View.INVISIBLE);
                                        leaveStartTimeText.setVisibility(View.VISIBLE);
                                        stepLayout.setVisibility(View.VISIBLE);
                                        int myStep = 0, otherStep = 0;
                                        for (int i = 0; i < players.size(); i++) {
                                            if (players.get(i).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                                                myStep = players.get(i).getStep();
                                            } else {
                                                otherStep = players.get(i).getStep();
                                            }
                                        }
                                        if (myStep > otherStep) {
                                            noAcceptImg.setImageResource(R.drawable.h_win_icon);
                                        } else if (myStep == otherStep) {
                                            noAcceptImg.setImageResource(R.drawable.equla_yy);
                                        } else {
                                            noAcceptImg.setImageResource(R.drawable.lose_yy);
                                        }
                                        leftStep.setText(myStep + "");
                                        rightStep.setText(otherStep + "");
                                    } else {
                                        centerText.setText("明日开启");
                                    }
                                    seeAllPkButton.setVisibility(View.VISIBLE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
                    asynctask.execute(hashMapUrl2, params);

                }
            });
        } else if (judge == 0 && myState == 0) {
            if (TimeHelper.isToday(lqswHealthMatch.getStartTime())) {

            } else {
                centerText.setText("明日开启");
            }
            MyHistoryGame();
            seeAllPkButton.setVisibility(View.VISIBLE);
        }

        if (state == 1) {
            historyWinLayout.setVisibility(View.INVISIBLE);
            for (int i = 0; i < players.size(); i++) {
                if (players.get(i).getIsAccept() == 0 && players.get(i).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                    myState = 1;
                }
                if (players.get(i).getIsAccept() == 0 && players.get(i).getUserId() != UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                    //centerText.setText("等待对方接受PK");  pk图
                    noAcceptLayout.setVisibility(View.VISIBLE);
                    noAcceptImg.setVisibility(View.VISIBLE);
                    judge++;
                }
            }
            //leaveStartTimeText.setText("距离比赛结束还有" + TimeHelper.getMyFriendCountDownTime(lqswHealthMatch.getEndTime()));
            task = new TimerTask() {
                @Override
                public void run() {

                    runOnUiThread(new Runnable() {      // UI thread
                        @Override
                        public void run() {
                            leaveStartTimeText.setVisibility(View.VISIBLE);
                            leaveStartTimeText.setText("距离比赛结束还有" + TimeHelper.getMyFriendCountDownTime(lqswHealthMatch.getEndTime()));
                        }
                    });
                }
            };
            timer.schedule(task, 1000, 1000);
        }
//        else if (state == 2) {
//            for (int i = 0; i < players.size(); i++) {
//                if (players.get(i).getIsAccept() == 0 && players.get(i).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
//                    myState = 1;
//                }
//                if (players.get(i).getIsAccept() == 0 && players.get(i).getUserId() != UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
//                    //centerText.setText("等待对方接受PK");
//                    noAcceptLayout.setVisibility(View.VISIBLE);
//                    noAcceptImg.setVisibility(View.VISIBLE);
//                    judge++;
//                }
//            }
//            //leaveStartTimeText.setText("距离比赛结束还有" + TimeHelper.getMyFriendCountDownTime(lqswHealthMatch.getEndTime()));
//
//        }
        else if (state == 3 || state == 2) {
            if (state == 2) {
                task = new TimerTask() {
                    @Override
                    public void run() {

                        runOnUiThread(new Runnable() {      // UI thread
                            @Override
                            public void run() {
                                leaveStartTimeText.setVisibility(View.VISIBLE);
                                leaveStartTimeText.setText("距离比赛结束还有" + TimeHelper.getMyFriendCountDownTime(lqswHealthMatch.getEndTime()));
                            }
                        });
                    }
                };
                timer.schedule(task, 1000, 1000);
                seeAllPkButton.setVisibility(View.VISIBLE);
            } else {
                seeAllPkButton.setVisibility(View.INVISIBLE);
                leaveStartTimeText.setVisibility(View.INVISIBLE);
            }
            noAcceptImg.setVisibility(View.VISIBLE);
            centerText.setVisibility(View.INVISIBLE);
            stepLayout.setVisibility(View.VISIBLE);
            int myStep = 0, otherStep = 0;
            for (int i = 0; i < players.size(); i++) {
                if (players.get(i).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                    myStep = players.get(i).getStep();
                } else {
                    otherStep = players.get(i).getStep();
                }
            }
            if (myStep > otherStep) {
                noAcceptImg.setImageResource(R.drawable.h_win_icon);
            } else if (myStep == otherStep) {
                noAcceptImg.setImageResource(R.drawable.equla_yy);
            } else {
                noAcceptImg.setImageResource(R.drawable.lose_yy);
            }
            leftStep.setText(myStep + "");
            rightStep.setText(otherStep + "");
            MyHistoryGame();
        } else {//失效
            centerText.setVisibility(View.INVISIBLE);
            historyWinLayout.setVisibility(View.INVISIBLE);
            seeAllPkButton.setVisibility(View.INVISIBLE);
            noAcceptLayout.setVisibility(View.INVISIBLE);
            noAcceptImg.setVisibility(View.VISIBLE);
            leaveStartTimeText.setVisibility(View.INVISIBLE);
            noAcceptImg.setImageResource(R.drawable.no_result_game);
            if (hmMatch.getLqswHealthMatch().getOwnerId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                pkText.setText("重新发起比赛");
                pkButton.setVisibility(View.VISIBLE);
                pkButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap<String, String> params = new HashMap<>();
                        params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
                        params.put("enterpriseId", AppConfig.getEnterpriseId());
                        params.put("matchId", hmMatch.getLqswHealthMatch().getMatchId() + "");
                        String mStartTime = TimeHelper.getMyFriendPKStart() + "";
                        String mEndTime = TimeHelper.getMyFriendPKEnd(TimeHelper.getMyFriendPKStart()) + "";
                        params.put("startTime", mStartTime);
                        params.put("endTime", mEndTime);
                        String unstartUrl = "/hzlqswserver/health/game/update";
                        HashMap<String, String> hashMapUrl2 = new HashMap<>();
                        hashMapUrl2.put("url", unstartUrl);
                        MyAsynctask asynctask = new MyAsynctask(FriendPKDetailActivity.this, new MyAsynctask.RequestListener() {
                            @Override
                            public void requestSuccess(String result) {
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                    String res = jsonObject.optString("resultCode");
                                    if ("1000".equals(res)) {
                                        Toast.makeText(FriendPKDetailActivity.this, "发起成功", Toast.LENGTH_LONG).show();
                                        pkButton.setVisibility(View.INVISIBLE);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                        asynctask.execute(hashMapUrl2, params);

                    }
                });
            }

        }

        for (int i = 0; i < players.size(); i++) {
            if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(i).getUserId()) {
                leftNameText.setText("我");
                if (!TextUtils.isEmpty(players.get(i).getUserHead())) {
                    Picasso.with(this).load(players.get(i).getUserHead()).into(leftHeadIconImg);
                }
            } else {
                rightNameText.setText(players.get(i).getNickName());
                if (!TextUtils.isEmpty(players.get(i).getUserHead())) {
                    Picasso.with(this).load(players.get(i).getUserHead()).into(rightHeadIconImg);
                }
            }
        }

    }

    public void MyHistoryGame() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        params.put("enterpriseId", AppConfig.getEnterpriseId());
        int friendId = 0;
        for (int i = 0; i < players.size(); i++) {
            if (players.get(i).getUserId() != UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                friendId = players.get(i).getUserId();
            }
        }
        params.put("friendId", friendId + "");
        String unstartUrl = "hzlqswserver/health/game/getFriendMatchHitory";
        HashMap<String, String> hashMapUrl2 = new HashMap<>();
        hashMapUrl2.put("url", unstartUrl);
        MyAsynctask asynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("returnObject");
                    Log.i("darren2", res);
                    historyWinLayout.setVisibility(View.VISIBLE);

                    seeAllPkButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    HMOneFriendMatchDetailsDto hmFriendMatchDetailsDto = HMOneFriendMatchDetailsDto.parserJson(res);
                    leftDailyStep.setText(hmFriendMatchDetailsDto.getHMUserDailyStep() + "");
                    rightDailyStep.setText(hmFriendMatchDetailsDto.getHMFriendDailyStep() + "");
                    leftDailyW.setText(hmFriendMatchDetailsDto.getHMFriendMatchDetails().getWin() + "");
                    leftL.setText(hmFriendMatchDetailsDto.getHMFriendMatchDetails().getLose() + "");
                    leftD.setText(hmFriendMatchDetailsDto.getHMFriendMatchDetails().getDraw() + "");
                    rightL.setText(hmFriendMatchDetailsDto.getHMFriendMatchDetails().getWin() + "");
                    rightW.setText(hmFriendMatchDetailsDto.getHMFriendMatchDetails().getLose() + "");
                    rightD.setText(hmFriendMatchDetailsDto.getHMFriendMatchDetails().getDraw() + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        asynctask.execute(hashMapUrl2, params);
    }
}
